// admin/system/dao/sys_post_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysPostDao 岗位数据访问接口
type SysPostDao interface {
	Create(post *model.SysPost) error
	GetByID(id int64) (*model.SysPost, error)
	Update(post *model.SysPost) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysPost, int64, error)
	ListAll() ([]*model.SysPost, error)
	ListByUserID(userID int64) ([]*model.SysPost, error)
}

type sysPostDao struct {
	db *gorm.DB
}

// NewSysPostDao 创建岗位数据访问实例
func NewSysPostDao() SysPostDao {
	return &sysPostDao{
		db: database.GetDB(),
	}
}

func (p *sysPostDao) Create(post *model.SysPost) error {
	logger.Info("创建岗位", zap.Int64("post_id", post.PostID))
	return p.db.Create(post).Error
}

func (p *sysPostDao) GetByID(id int64) (*model.SysPost, error) {
	logger.Debug("根据ID获取岗位", zap.Int64("post_id", id))
	var post model.SysPost
	err := p.db.Where("post_id = ? AND status = '0'", id).First(&post).Error
	return &post, err
}

func (p *sysPostDao) Update(post *model.SysPost) error {
	logger.Info("更新岗位", zap.Int64("post_id", post.PostID))
	return p.db.Save(post).Error
}

func (p *sysPostDao) Delete(id int64) error {
	logger.Info("删除岗位", zap.Int64("post_id", id))
	return p.db.Where("post_id = ?", id).Delete(&model.SysPost{}).Error
}

func (p *sysPostDao) List(page, pageSize int) ([]*model.SysPost, int64, error) {
	logger.Debug("获取岗位列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var posts []*model.SysPost
	var total int64

	offset := (page - 1) * pageSize
	db := p.db.Model(&model.SysPost{}).Where("status = '0'")

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&posts).Error; err != nil {
		return nil, 0, err
	}

	return posts, total, nil
}

func (p *sysPostDao) ListAll() ([]*model.SysPost, error) {
	logger.Debug("获取所有岗位列表")
	var posts []*model.SysPost
	err := p.db.Where("status = '0'").Order("post_sort").Find(&posts).Error
	return posts, err
}

func (p *sysPostDao) ListByUserID(userID int64) ([]*model.SysPost, error) {
	logger.Debug("根据用户ID获取岗位列表", zap.Int64("user_id", userID))
	var posts []*model.SysPost
	err := p.db.
		Joins("LEFT JOIN sys_user_post up ON sys_post.post_id = up.post_id").
		Where("up.user_id = ? AND sys_post.status = '0'", userID).
		Order("sys_post.post_sort").
		Find(&posts).Error
	return posts, err
}
